package com.systemsjr.jrhabit;

import java.sql.SQLDataException;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseConnection {

	private static final String DATABASE_NAME = "jrhabit";
	private SQLiteDatabase database;
	private DatabaseOpenHelper databaseOpenHelper;

	public DatabaseConnection(Context context) {

		databaseOpenHelper = new DatabaseOpenHelper(context, DATABASE_NAME,	null, 1);
	}

	private class DatabaseOpenHelper extends SQLiteOpenHelper {

		public DatabaseOpenHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);

		}

		@Override
		public void onCreate(SQLiteDatabase db) {

			/*String createQuery = "CREATE TABLE hospitals (_id INTEGER PRIMARY_KEY AUTOINCREMENT,"
					+ "name TEXT, street TEXT, town TEXT, district TEXT, address TEXT, phone TEXT, email TEXT,"
					+ "facility_type  TEST);";
			db.execSQL(createQuery);*/
			
			/**
			 * CREATE  TABLE habit_monitor ("id" INTEGER PRIMARY KEY  AUTOINCREMENT  
			 * NOT NULL , "habit_fk" INTEGER NOT NULL , "date_completed" 
			 * DATETIME NOT NULL  DEFAULT CURRENT_TIMESTAMP)
			 * 
			 * CREATE  TABLE "main"."habit" ("id" INTEGER PRIMARY KEY  AUTOINCREMENT  
			 * NOT NULL , "habit" TEXT NOT NULL , "repeat" TEXT NOT NULL )
			 */
		}

		@Override
		public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {

		}

		
	}

	public void open() throws SQLException {
		database = databaseOpenHelper.getWritableDatabase();
	}

	public void close() {
		if (database != null) {
			database.close();
		}
	}

	public Cursor getOneHabit(Long id) {
		return database.query("hospitals", null, "id", null, null, null, null);
	}
	
	public void insertHabit(String habit, String repeat){
		
		ContentValues newContent = new ContentValues();
		newContent.put("habit", habit);
		newContent.put("repeat", repeat);
		open();
		database.insert("habits", null, newContent);
		close();
		
	}
	
	public void updateHabit(long id, String habit, String repeat){
		
		ContentValues newContent = new ContentValues();
		newContent.put("habit", habit);
		newContent.put("repeat", repeat);
		open();
		database.update("habits", newContent, " id="+id, null);
		close();
	}
	
	public void deleteHabit(long id){
		open();
		database.delete("habits", " id=" + id, null);
		close();
	}
	
	public Cursor getAllHabit() {

		return database.query("habits", new String[] { "id", "habit", "repeat"}, "name",
				null, null, null, "name");
	}
}
